package com.newsmanagement.controller.user;

import com.newsmanagement.domain.pojo.SlauBatch;
import com.newsmanagement.mapper.SlauSlauBatchMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/slauBatch")
public class SlauBatchController {

    @Autowired
    private SlauSlauBatchMapper slauSlauBatchMapper;

    /**
     * 检查产品批号是否已存在
     */
    @GetMapping("/checkBatchId")
    public Map<String, Object> checkBatchId(@RequestParam String batchId) {
        boolean exists = slauSlauBatchMapper.checkBatchIdExists(batchId) > 0;
        Map<String, Object> result = new HashMap<>();
        result.put("exists", exists);
        return result;
    }

    /**
     * 检查屠宰企业编号是否存在
     */
    @GetMapping("/checkSlauId")
    public Map<String, Object> checkSlauId(@RequestParam String slauId) {
        boolean exists = slauSlauBatchMapper.checkSlauIdExists(slauId) > 0;
        Map<String, Object> result = new HashMap<>();
        result.put("exists", exists);
        return result;
    }

    /**
     * 创建新的产品批号
     */
    @PostMapping("/create")
    public Map<String, Object> createSlauBatch(@RequestBody Map<String, Object> formData) {
        Map<String, Object> result = new HashMap<>();

        try {
            String batchId = (String) formData.get("batchId");

            // 再次检查批号是否存在（防止并发情况）
            boolean exists = slauSlauBatchMapper.checkBatchIdExists(batchId) > 0;
            if (exists) {
                result.put("success", false);
                result.put("message", "产品批号已存在");
                return result;
            }

            // 创建新的屠宰批号记录
            SlauBatch slauBatch = new SlauBatch();
            slauBatch.setBatchId(batchId);

            // 设置屠宰企业编号
            if (formData.get("slauId") != null) {
                slauBatch.setSlauId(Integer.parseInt(formData.get("slauId").toString()));
            }

            // 设置养殖企业进场编号
            if (formData.get("fbId") != null) {
                slauBatch.setFbId(Integer.parseInt(formData.get("fbId").toString()));
            }

            slauBatch.setType((String) formData.get("type"));
            slauBatch.setQuaId((String) formData.get("quaId"));
            slauBatch.setTestName((String) formData.get("testName"));

            // 设置检验日期
            if (formData.get("batchDate") != null) {
                String batchDateStr = (String) formData.get("batchDate");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                slauBatch.setBatchDate(sdf.parse(batchDateStr));
            } else {
                slauBatch.setBatchDate(new Date());
            }

            slauBatch.setState(1); // 新建状态
            slauBatch.setRemarks(""); // 空备注

            // 插入数据库
            int insertResult = slauSlauBatchMapper.insertSlauBatch(slauBatch);

            if (insertResult > 0) {
                result.put("success", true);
                result.put("message", "创建成功");
            } else {
                result.put("success", false);
                result.put("message", "创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 获取所有产品批号列表
     */
    @GetMapping("/list")
    public List<SlauBatch> getAllSlauBatches() {
        return slauSlauBatchMapper.selectAllSlauBatches();
    }

    /**
     * 根据状态获取产品批号列表
     */
    @GetMapping("/listByState")
    public List<SlauBatch> getSlauBatchesByState(@RequestParam Integer state) {
        return slauSlauBatchMapper.selectSlauBatchesByState(state);
    }

    /**
     * 获取状态统计
     */
    @GetMapping("/statusCounts")
    public Map<Integer, Long> getStatusCounts() {
        List<Map<String, Object>> resultList = slauSlauBatchMapper.selectStatusCounts();
        Map<Integer, Long> resultMap = new HashMap<>();

        for (Map<String, Object> item : resultList) {
            Integer state = (Integer) item.get("state");
            Long count = ((Number) item.get("count")).longValue();
            resultMap.put(state, count);
        }

        return resultMap;
    }

    /**
     * 删除产品批号
     */
    @DeleteMapping("/delete/{batchId}")
    public Map<String, Object> deleteSlauBatch(@PathVariable String batchId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int deleteResult = slauSlauBatchMapper.deleteSlauBatch(batchId);
            if (deleteResult > 0) {
                result.put("success", true);
                result.put("message", "删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败，记录不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 更新产品批号 - 只更新发生变化的字段
     */
    @PutMapping("/update")
    public Map<String, Object> updateSlauBatch(@RequestBody Map<String, Object> formData) {
        Map<String, Object> result = new HashMap<>();

        try {
            String batchId = (String) formData.get("batchId");

            // 检查批号是否存在
            boolean exists = slauSlauBatchMapper.checkBatchIdExists(batchId) > 0;
            if (!exists) {
                result.put("success", false);
                result.put("message", "产品批号不存在");
                return result;
            }

            // 获取原始记录
            SlauBatch originalBatch = slauSlauBatchMapper.selectSlauBatchById(batchId);
            if (originalBatch == null) {
                result.put("success", false);
                result.put("message", "产品批号不存在");
                return result;
            }

            // 创建更新对象
            SlauBatch updateBatch = new SlauBatch();
            updateBatch.setBatchId(batchId);

            // 设置原始状态值，确保状态不变
            if (formData.get("originalState") != null) {
                updateBatch.setState(Integer.parseInt(formData.get("originalState").toString()));
            } else {
                // 如果没有提供原始状态，使用数据库中的状态
                updateBatch.setState(originalBatch.getState());
            }

            boolean hasChanges = false;
            List<String> changedFields = new ArrayList<>();

            // 检查屠宰企业编号是否变化
            if (formData.get("slauId") != null) {
                Integer newSlauId = Integer.parseInt(formData.get("slauId").toString());
                if (!newSlauId.equals(originalBatch.getSlauId())) {
                    updateBatch.setSlauId(newSlauId);
                    hasChanges = true;
                    changedFields.add("屠宰企业编号");
                }
            }

            // 检查养殖企业进场编号是否变化
            if (formData.get("fbId") != null) {
                Integer newFbId = Integer.parseInt(formData.get("fbId").toString());
                if (!newFbId.equals(originalBatch.getFbId())) {
                    updateBatch.setFbId(newFbId);
                    hasChanges = true;
                    changedFields.add("养殖企业进场编号");
                }
            }

            // 检查产品品种是否变化
            String newType = (String) formData.get("type");
            if (newType != null && !newType.equals(originalBatch.getType())) {
                updateBatch.setType(newType);
                hasChanges = true;
                changedFields.add("产品品种");
            }

            // 检查合格证编号是否变化
            String newQuaId = (String) formData.get("quaId");
            if (newQuaId != null && !newQuaId.equals(originalBatch.getQuaId())) {
                updateBatch.setQuaId(newQuaId);
                hasChanges = true;
                changedFields.add("合格证编号");
            }

            // 检查检验员名称是否变化
            String newTestName = (String) formData.get("testName");
            if (newTestName != null && !newTestName.equals(originalBatch.getTestName())) {
                updateBatch.setTestName(newTestName);
                hasChanges = true;
                changedFields.add("检验员名称");
            }

            // 检查检验日期是否变化
            if (formData.get("batchDate") != null) {
                String batchDateStr = (String) formData.get("batchDate");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date newBatchDate = sdf.parse(batchDateStr);

                // 比较日期（忽略时间部分）
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String originalDateStr = dateFormat.format(originalBatch.getBatchDate());
                String newDateStr = dateFormat.format(newBatchDate);

                if (!newDateStr.equals(originalDateStr)) {
                    updateBatch.setBatchDate(newBatchDate);
                    hasChanges = true;
                    changedFields.add("检验日期");
                }
            }

            // 如果没有变化，直接返回成功
            if (!hasChanges) {
                result.put("success", true);
                result.put("message", "数据未发生变化");
                result.put("changed", false);
                return result;
            }

            // 更新数据库
            int updateResult = slauSlauBatchMapper.updateSlauBatchSelective(updateBatch);

            if (updateResult > 0) {
                result.put("success", true);
                result.put("message", "更新成功！");
                result.put("changed", true);
                result.put("changedFields", changedFields);
            } else {
                result.put("success", false);
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 下架产品批号
     */
    @PutMapping("/shelf/{batchId}")
    public Map<String, Object> shelfSlauBatch(@PathVariable String batchId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查批号是否存在
            boolean exists = slauSlauBatchMapper.checkBatchIdExists(batchId) > 0;
            if (!exists) {
                result.put("success", false);
                result.put("message", "产品批号不存在");
                return result;
            }

            // 获取原始记录
            SlauBatch originalBatch = slauSlauBatchMapper.selectSlauBatchById(batchId);
            if (originalBatch == null) {
                result.put("success", false);
                result.put("message", "产品批号不存在");
                return result;
            }

            // 检查当前状态是否为已确认（3）
            if (originalBatch.getState() != 3) {
                result.put("success", false);
                result.put("message", "只有已确认状态的产品批号才能下架");
                return result;
            }

            // 创建更新对象，只更新状态为下架（4）
            SlauBatch updateBatch = new SlauBatch();
            updateBatch.setBatchId(batchId);
            updateBatch.setState(4); // 下架状态

            // 更新数据库
            int updateResult = slauSlauBatchMapper.updateSlauBatchSelective(updateBatch);

            if (updateResult > 0) {
                result.put("success", true);
                result.put("message", "下架成功");
            } else {
                result.put("success", false);
                result.put("message", "下架失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 提交产品批号（新建 → 待确认）
     */
    @PutMapping("/submit/{batchId}")
    public Map<String, Object> submitSlauBatch(@PathVariable String batchId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查批号是否存在
            boolean exists = slauSlauBatchMapper.checkBatchIdExists(batchId) > 0;
            if (!exists) {
                result.put("success", false);
                result.put("message", "产品批号不存在");
                return result;
            }

            // 获取原始记录
            SlauBatch originalBatch = slauSlauBatchMapper.selectSlauBatchById(batchId);
            if (originalBatch == null) {
                result.put("success", false);
                result.put("message", "产品批号不存在");
                return result;
            }

            // 检查当前状态是否为新建（1）
            if (originalBatch.getState() != 1) {
                result.put("success", false);
                result.put("message", "只有新建状态的产品批号才能提交");
                return result;
            }

            // 创建更新对象，只更新状态为待确认（2）
            SlauBatch updateBatch = new SlauBatch();
            updateBatch.setBatchId(batchId);
            updateBatch.setState(2); // 待确认状态

            // 更新数据库
            int updateResult = slauSlauBatchMapper.updateSlauBatchSelective(updateBatch);

            if (updateResult > 0) {
                result.put("success", true);
                result.put("message", "提交成功");
            } else {
                result.put("success", false);
                result.put("message", "提交失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return result;
    }
}